# Welcome the user to the quiz program
# Explain that they will answer multiple-choice questions
def welcome_message():
    print("=" * 50)
    print(" Welcome to the General Knowledge Quiz! ")
    print("\nRules:")
    print("- You will answer 5 multiple-choice questions.")
    print("- Enter the letter (A/B/C/D) of your answer.")
    print("- Your score will be calculated at the end.")
    print("=" * 50)

# Initialize a score counter to keep track of correct answers
def get_quiz_questions():
    return [
        {
            "question": "1. Which planet is known as the Red Planet?",
            "options": {"A": "Venus", "B": "Mars", "C": "Jupiter", "D": "Saturn"},
            "correct": "B"
        },
        {
            "question": "2. What is the largest ocean on Earth?",
            "options": {"A": "Atlantic", "B": "Indian", "C": "Pacific", "D": "Arctic"},
            "correct": "C"
        },
        {
            "question": "3. Which programming language is this quiz written in?",
            "options": {"A": "Java", "B": "Python", "C": "C++", "D": "JavaScript"},
            "correct": "B"
        },
        {
            "question": "4. What is the chemical symbol for water?",
            "options": {"A": "H2O", "B": "CO2", "C": "O2", "D": "NaCl"},
            "correct": "A"
        },
        {
            "question": "5. Which country hosted the 2020 Summer Olympics?",
            "options": {"A": "China", "B": "Japan", "C": "Brazil", "D": "South Korea"},
            "correct": "B"
        }
    ]

# Present the first question
# Display the question text and the multiple-choice answers
# you can think of questions yourself, or find them online
def run_quiz(username):
    questions = get_quiz_questions()
    score = 0 
    
    for q in questions:
        print(f"\n{q['question']}")
        for option, content in sorted(q["options"].items()):
            print(f"   {option}. {content}")
# Get the user's input for their answer to the first question
while True:
            user_answer = input("Your answer (A/B/C/D): ").strip().upper()
            if user_answer in q["options"].keys():
                break
            print("Invalid input! Please enter A, B, C, or D.")
# Check if the answer is correct
# If the answer is correct, print a success message and increase the score
# If the answer is incorrect, print the correct answer
            if user_answer == q["correct"]:
                print(" Correct!")
                score += 1
            else:
                print(f"Wrong answer. The correct answer is {q['correct']}.")
# Repeat the above steps for additional questions (Question 2, Question 3, etc.)

# After all questions are answered, display the final score to the user
# Thank them for participating in the quiz

###### Extensions ######
def display_leaderboard(leaderboard):
    """显示排行榜"""
    print("\n Leaderboard (Top 5 Scores) ")
    if not leaderboard:
        print("   No scores yet. Be the first to take the quiz!")
        return
    for rank, (score, username) in enumerate(leaderboard, 1):
        print(f"   {rank}. {username}: {score}/5")


def main_menu():
    leaderboard = []  
    
    while True:
        print("\n" + "=" * 30)
        print("📋 Main Menu")
        print("1. Start Quiz")
        print("2. View Leaderboard")
        print("3. Exit")
        print("=" * 30)
        
        while True:
            choice = input("Enter your choice (1/2/3): ").strip()
            if choice in ["1", "2", "3"]:
                break
            print("Invalid input! Please enter 1, 2, or 3.")
        
        if choice == "1":
            username = input("\nEnter your username: ").strip()
            while not username:
                username = input("Username cannot be empty! Enter again: ").strip()
            score = run_quiz(username)
            leaderboard = update_leaderboard(username, score, leaderboard) # type: ignore
            retry = input("\nDo you want to take the quiz again? (Y/N): ").strip().upper()
            if retry != "Y":
                print(f"Thank you for participating, {username}!")
        
        elif choice == "2":
            display_leaderboard(leaderboard)
        
        elif choice == "3":
            print("\n Goodbye! Thanks for using the Quiz Program.")
            break

if __name__ == "__main__":
    welcome_message()
    main_menu()
# Use a loop to let people re-try the quiz
# create a leaderboard which stores users with the highest score
# Create a menu to let people access the leaderboard or the quiz
# Modularise the code to make it shorter and more maintainable